import pandas as pd
import json
from datetime import datetime, timedelta

# 设置文件路径
file_path = r"e:\Projects\program-py\LEARN-数据分析\CASE-dashboard_epidemic\香港各区疫情数据_20250322.xlsx"


def process_data_for_dashboard():
    """处理数据并生成适合大屏显示的数据格式"""

    # 读取数据
    df = pd.read_excel(file_path)
    print(f"数据加载成功，形状: {df.shape}")

    # 1. 处理时间序列数据
    # 按日期汇总数据
    daily_data = df.groupby('报告日期').agg({
        '新增确诊': 'sum',
        '累计确诊': 'max',
        '现存确诊': 'sum',
        '新增康复': 'sum',
        '累计康复': 'max',
        '新增死亡': 'sum',
        '累计死亡': 'max'
    }).reset_index()

    # 转换日期格式
    daily_data['报告日期'] = pd.to_datetime(daily_data['报告日期'])
    daily_data = daily_data.sort_values('报告日期')

    # 2. 处理地区数据
    # 获取最新日期的地区数据
    latest_date = df['报告日期'].max()
    regional_data = df[df['报告日期'] == latest_date][['地区名称', '累计确诊', '新增确诊', '风险等级']].copy()

    # 按累计确诊排序
    regional_data = regional_data.sort_values('累计确诊', ascending=False)

    # 3. 处理风险等级数据
    risk_data = df['风险等级'].value_counts().reset_index()
    risk_data.columns = ['风险等级', '地区数量']

    # 4. 准备图表数据
    chart_data = {
        # 时间序列数据
        'dates': daily_data['报告日期'].dt.strftime('%Y-%m-%d').tolist(),
        'newConfirmed': daily_data['新增确诊'].tolist(),
        'totalConfirmed': daily_data['累计确诊'].tolist(),
        'activeCases': daily_data['现存确诊'].tolist(),
        'newRecovered': daily_data['新增康复'].tolist(),
        'totalRecovered': daily_data['累计康复'].tolist(),
        'totalDeaths': daily_data['累计死亡'].tolist(),

        # 地区数据
        'regions': regional_data['地区名称'].tolist(),
        'regionConfirmed': regional_data['累计确诊'].tolist(),
        'regionNewConfirmed': regional_data['新增确诊'].tolist(),

        # 风险等级数据
        'riskLevels': risk_data['风险等级'].tolist(),
        'riskCounts': risk_data['地区数量'].tolist(),

        # 统计数据
        'stats': {
            'totalConfirmed': int(df['累计确诊'].max()),
            'newConfirmed': int(daily_data['新增确诊'].iloc[-1]),
            'totalDeaths': int(df['累计死亡'].max()),
            'activeCases': int(daily_data['现存确诊'].iloc[-1]),
            'totalRecovered': int(df['累计康复'].max()),
            'totalRegions': int(df['地区名称'].nunique()),
            'latestDate': str(latest_date)
        }
    }

    return chart_data


def calculate_growth_rates(new_confirmed):
    """计算增长率"""
    growth_rates = []
    for i in range(1, len(new_confirmed)):
        if new_confirmed[i - 1] == 0:
            growth_rate = 0
        else:
            growth_rate = ((new_confirmed[i] - new_confirmed[i - 1]) / new_confirmed[i - 1]) * 100
        growth_rates.append(round(growth_rate, 1))
    return [0] + growth_rates  # 第一天增长率为0


def create_dashboard_html(chart_data):
    """创建包含真实数据的高级大屏HTML文件"""

    # 计算增长率数据
    growth_rates = calculate_growth_rates(chart_data['newConfirmed'])

    # 准备JSON数据
    chart_data_json = json.dumps(chart_data, ensure_ascii=False)
    growth_rates_json = json.dumps(growth_rates, ensure_ascii=False)

    html_template = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>香港疫情实时监控大屏</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}

        body {{
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%);
            color: #fff;
            overflow: hidden;
        }}

        .dashboard {{
            width: 100vw;
            height: 100vh;
            padding: 15px;
            display: grid;
            grid-template-columns: 1fr 2fr 1fr;
            grid-template-rows: auto 1fr 1fr auto;
            gap: 15px;
        }}

        /* 顶部标题栏 */
        .header {{
            grid-column: 1 / -1;
            background: rgba(0, 50, 100, 0.3);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            padding: 15px 30px;
            border: 1px solid rgba(0, 150, 255, 0.3);
            display: flex;
            justify-content: space-between;
            align-items: center;
            animation: fadeInDown 1s ease-out;
        }}

        .header h1 {{
            font-size: 2.2em;
            font-weight: bold;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            background: linear-gradient(45deg, #00d4ff, #0099ff);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }}

        .update-info {{
            display: flex;
            align-items: center;
            gap: 20px;
        }}

        .update-time {{
            background: rgba(0, 150, 255, 0.2);
            padding: 8px 15px;
            border-radius: 20px;
            border: 1px solid rgba(0, 150, 255, 0.4);
            font-size: 0.9em;
        }}

        /* 核心指标展示 */
        .metrics-row {{
            grid-column: 1 / -1;
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 15px;
        }}

        .metric-card {{
            background: rgba(0, 50, 100, 0.2);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            padding: 20px;
            border: 1px solid rgba(0, 150, 255, 0.3);
            text-align: center;
            position: relative;
            overflow: hidden;
            animation: fadeInUp 1s ease-out;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }}

        .metric-card:hover {{
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0, 150, 255, 0.3);
        }}

        .metric-card::before {{
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, #00d4ff, #0099ff);
        }}

        .metric-value {{
            font-size: 2.5em;
            font-weight: bold;
            margin: 10px 0;
            color: #00d4ff;
            text-shadow: 0 0 10px rgba(0, 212, 255, 0.5);
        }}

        .metric-label {{
            font-size: 0.9em;
            opacity: 0.9;
            margin-bottom: 5px;
        }}

        .metric-change {{
            font-size: 0.8em;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
        }}

        .metric-up {{
            color: #ff6b6b;
        }}

        .metric-down {{
            color: #6bcf7f;
        }}

        /* 中心区域 */
        .center-left {{
            background: rgba(0, 50, 100, 0.2);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            padding: 20px;
            border: 1px solid rgba(0, 150, 255, 0.3);
            animation: fadeInLeft 1s ease-out;
        }}

        .center-right {{
            display: flex;
            flex-direction: column;
            gap: 15px;
        }}

        .chart-container {{
            background: rgba(0, 50, 100, 0.2);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            padding: 20px;
            border: 1px solid rgba(0, 150, 255, 0.3);
            animation: fadeInRight 1s ease-out;
            flex: 1;
            display: flex;
            flex-direction: column;
        }}

        .chart-title {{
            font-size: 1.2em;
            font-weight: bold;
            margin-bottom: 15px;
            text-align: center;
            color: #00d4ff;
            text-shadow: 0 0 5px rgba(0, 212, 255, 0.3);
        }}

        .chart {{
            flex: 1;
            min-height: 0;
        }}

        /* 右侧区域 */
        .right-panel {{
            display: flex;
            flex-direction: column;
            gap: 15px;
        }}

        /* 底部趋势区 */
        .trends-section {{
            grid-column: 1 / -1;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }}

        /* 控制面板 */
        .controls {{
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(0, 50, 100, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 10px;
            padding: 15px;
            border: 1px solid rgba(0, 150, 255, 0.3);
            z-index: 1000;
            display: flex;
            gap: 10px;
        }}

        .control-btn {{
            background: rgba(0, 150, 255, 0.2);
            border: 1px solid rgba(0, 150, 255, 0.4);
            color: #fff;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }}

        .control-btn:hover {{
            background: rgba(0, 150, 255, 0.4);
            transform: translateY(-2px);
        }}

        /* 动画效果 */
        @keyframes fadeInDown {{
            from {{
                opacity: 0;
                transform: translateY(-30px);
            }}
            to {{
                opacity: 1;
                transform: translateY(0);
            }}
        }}

        @keyframes fadeInUp {{
            from {{
                opacity: 0;
                transform: translateY(30px);
            }}
            to {{
                opacity: 1;
                transform: translateY(0);
            }}
        }}

        @keyframes fadeInLeft {{
            from {{
                opacity: 0;
                transform: translateX(-30px);
            }}
            to {{
                opacity: 1;
                transform: translateX(0);
            }}
        }}

        @keyframes fadeInRight {{
            from {{
                opacity: 0;
                transform: translateX(30px);
            }}
            to {{
                opacity: 1;
                transform: translateX(0);
            }}
        }}
    </style>
</head>
<body>
    <div class="dashboard">
        <!-- 顶部标题栏 -->
        <div class="header">
            <h1>🏥 香港疫情实时监控大屏</h1>
            <div class="update-info">
                <div class="update-time">
                    数据更新时间: <span id="updateTime"></span>
                </div>
            </div>
        </div>

        <!-- 核心指标展示 -->
        <div class="metrics-row">
            <div class="metric-card">
                <div class="metric-label">今日新增确诊</div>
                <div class="metric-value" id="todayConfirmed">0</div>
                <div class="metric-change metric-up">
                    <span>↑</span>
                    <span>+0%</span>
                </div>
            </div>
            <div class="metric-card">
                <div class="metric-label">累计确诊总数</div>
                <div class="metric-value" id="totalConfirmed">0</div>
                <div class="metric-change metric-up">
                    <span>↑</span>
                    <span>+0%</span>
                </div>
            </div>
            <div class="metric-card">
                <div class="metric-label">当前活跃病例</div>
                <div class="metric-value" id="activeCases">0</div>
                <div class="metric-change metric-down">
                    <span>↓</span>
                    <span>-0%</span>
                </div>
            </div>
            <div class="metric-card">
                <div class="metric-label">累计康复人数</div>
                <div class="metric-value" id="totalRecovered">0</div>
                <div class="metric-change metric-up">
                    <span>↑</span>
                    <span>+0%</span>
                </div>
            </div>
            <div class="metric-card">
                <div class="metric-label">累计死亡人数</div>
                <div class="metric-value" id="totalDeaths">0</div>
                <div class="metric-change">
                    <span>→</span>
                    <span>0%</span>
                </div>
            </div>
        </div>

        <!-- 中心区域左侧：地理分布图 -->
        <div class="center-left">
            <div class="chart-title">🗺️ 香港地区疫情热力图</div>
            <div id="mapChart" class="chart"></div>
        </div>

        <!-- 中心区域右侧上部：每日新增与累计确诊 -->
        <div class="center-right">
            <div class="chart-container">
                <div class="chart-title">📈 每日新增与累计确诊趋势</div>
                <div id="trendChart" class="chart"></div>
            </div>

            <!-- 各区域疫情对比 -->
            <div class="chart-container">
                <div class="chart-title">🏘️ 各区域疫情对比</div>
                <div id="regionChart" class="chart"></div>
            </div>
        </div>

        <!-- 右侧面板 -->
        <div class="right-panel">
            <!-- 风险预警看板 -->
            <div class="chart-container">
                <div class="chart-title">⚠️ 风险等级分布</div>
                <div id="riskChart" class="chart"></div>
            </div>

            <!-- 关键指标预警 -->
            <div class="chart-container">
                <div class="chart-title">🚨 高风险区域</div>
                <div id="warningChart" class="chart"></div>
            </div>
        </div>

        <!-- 底部趋势区 -->
        <div class="trends-section">
            <!-- 增长率变化曲线 -->
            <div class="chart-container">
                <div class="chart-title">📊 增长率变化趋势</div>
                <div id="growthChart" class="chart"></div>
            </div>

            <!-- 活跃病例趋势 -->
            <div class="chart-container">
                <div class="chart-title">📉 活跃病例趋势</div>
                <div id="activeTrendChart" class="chart"></div>
            </div>
        </div>
    </div>

    <!-- 控制面板 -->
    <div class="controls">
        <button class="control-btn" onclick="changeTimeRange('7d')">7天</button>
        <button class="control-btn" onclick="changeTimeRange('30d')">30天</button>
        <button class="control-btn" onclick="changeTimeRange('90d')">90天</button>
        <button class="control-btn" onclick="exportData()">导出数据</button>
    </div>

    <script>
        // 真实数据
        const chartData = {chart_data_json};

        // 计算增长率
        const growthRates = {growth_rates_json};

        // 初始化所有图表
        function initAllCharts() {{
            // 更新统计数据
            document.getElementById('todayConfirmed').textContent = chartData.stats.newConfirmed.toLocaleString();
            document.getElementById('totalConfirmed').textContent = chartData.stats.totalConfirmed.toLocaleString();
            document.getElementById('activeCases').textContent = chartData.stats.activeCases.toLocaleString();
            document.getElementById('totalRecovered').textContent = chartData.stats.totalRecovered.toLocaleString();
            document.getElementById('totalDeaths').textContent = chartData.stats.totalDeaths.toLocaleString();
            document.getElementById('updateTime').textContent = chartData.stats.latestDate;

            initTrendChart();
            initRegionChart();
            initRiskChart();
            initWarningChart();
            initGrowthChart();
            initActiveTrendChart();
            initMapChart();
        }}

        // 1. 每日新增与累计确诊趋势图
        function initTrendChart() {{
            const chart = echarts.init(document.getElementById('trendChart'));
            const option = {{
                backgroundColor: 'transparent',
                tooltip: {{
                    trigger: 'axis',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    borderColor: '#00d4ff',
                    textStyle: {{ color: '#fff' }}
                }},
                legend: {{
                    data: ['每日新增', '累计确诊'],
                    textStyle: {{ color: '#fff' }},
                    top: 10
                }},
                grid: {{
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                }},
                xAxis: {{
                    type: 'category',
                    data: chartData.dates,
                    axisLine: {{ lineStyle: {{ color: '#00d4ff' }} }},
                    axisLabel: {{ 
                        color: '#fff',
                        rotate: 45,
                        interval: Math.floor(chartData.dates.length / 10)
                    }}
                }},
                yAxis: [
                    {{
                        type: 'value',
                        name: '每日新增',
                        position: 'left',
                        axisLine: {{ lineStyle: {{ color: '#00d4ff' }} }},
                        axisLabel: {{ color: '#fff' }},
                        splitLine: {{ lineStyle: {{ color: 'rgba(0, 212, 255, 0.1)' }} }}
                    }},
                    {{
                        type: 'value',
                        name: '累计确诊',
                        position: 'right',
                        axisLine: {{ lineStyle: {{ color: '#ff6b6b' }} }},
                        axisLabel: {{ color: '#fff' }}
                    }}
                ],
                series: [
                    {{
                        name: '每日新增',
                        type: 'bar',
                        yAxisIndex: 0,
                        data: chartData.newConfirmed,
                        itemStyle: {{
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {{ offset: 0, color: '#00d4ff' }},
                                {{ offset: 1, color: '#0099ff' }}
                            ])
                        }},
                        animationDelay: function (idx) {{
                            return idx * 10;
                        }}
                    }},
                    {{
                        name: '累计确诊',
                        type: 'line',
                        yAxisIndex: 1,
                        data: chartData.totalConfirmed,
                        smooth: true,
                        lineStyle: {{
                            color: '#ff6b6b',
                            width: 3
                        }},
                        areaStyle: {{
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {{ offset: 0, color: 'rgba(255, 107, 107, 0.3)' }},
                                {{ offset: 1, color: 'rgba(255, 107, 107, 0.1)' }}
                            ])
                        }},
                        animationDelay: function (idx) {{
                            return idx * 10 + 100;
                        }}
                    }}
                ],
                animationEasing: 'elasticOut'
            }};
            chart.setOption(option);
        }}

        // 2. 各区域疫情对比图
        function initRegionChart() {{
            const chart = echarts.init(document.getElementById('regionChart'));
            const sortedData = chartData.regions.map((region, index) => ({{
                name: region,
                value: chartData.regionConfirmed[index]
            }})).sort((a, b) => b.value - a.value);

            const option = {{
                backgroundColor: 'transparent',
                tooltip: {{
                    trigger: 'axis',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    textStyle: {{ color: '#fff' }}
                }},
                grid: {{
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                }},
                xAxis: {{
                    type: 'value',
                    axisLine: {{ lineStyle: {{ color: '#00d4ff' }} }},
                    axisLabel: {{ color: '#fff' }},
                    splitLine: {{ lineStyle: {{ color: 'rgba(0, 212, 255, 0.1)' }} }}
                }},
                yAxis: {{
                    type: 'category',
                    data: sortedData.map(item => item.name),
                    axisLine: {{ lineStyle: {{ color: '#00d4ff' }} }},
                    axisLabel: {{ color: '#fff' }}
                }},
                series: [{{
                    type: 'bar',
                    data: sortedData,
                    itemStyle: {{
                        color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                            {{ offset: 0, color: '#00d4ff' }},
                            {{ offset: 1, color: '#0099ff' }}
                        ])
                    }},
                    animationDelay: function (idx) {{
                        return idx * 50;
                    }}
                }}],
                animationEasing: 'elasticOut'
            }};
            chart.setOption(option);
        }}

        // 3. 风险等级分布图
        function initRiskChart() {{
            const chart = echarts.init(document.getElementById('riskChart'));
            const option = {{
                backgroundColor: 'transparent',
                tooltip: {{
                    trigger: 'item',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    textStyle: {{ color: '#fff' }}
                }},
                series: [{{
                    type: 'pie',
                    radius: ['40%', '70%'],
                    data: chartData.riskLevels.map((level, index) => ({{
                        name: level,
                        value: chartData.riskCounts[index]
                    }})),
                    itemStyle: {{
                        color: function(params) {{
                            const colors = ['#6bcf7f', '#ffd93d', '#ff6b6b'];
                            return colors[params.dataIndex];
                        }}
                    }},
                    label: {{
                        color: '#fff',
                        formatter: '{{b}}\\n{{c}}个区域\\n({{d}}%)'
                    }},
                    animationType: 'expansion',
                    animationEasing: 'elasticOut'
                }}]
            }};
            chart.setOption(option);
        }}

        // 4. 高风险区域图表
        function initWarningChart() {{
            const chart = echarts.init(document.getElementById('warningChart'));
            const highRiskRegions = chartData.regions.slice(0, 5).map((region, index) => ({{
                name: region,
                value: chartData.regionNewConfirmed[index],
                risk: index < 2 ? '高' : '中'
            }}));

            const option = {{
                backgroundColor: 'transparent',
                tooltip: {{
                    trigger: 'item',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    textStyle: {{ color: '#fff' }}
                }},
                grid: {{
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                }},
                xAxis: {{
                    type: 'category',
                    data: highRiskRegions.map(item => item.name),
                    axisLine: {{ lineStyle: {{ color: '#00d4ff' }} }},
                    axisLabel: {{ 
                        color: '#fff',
                        rotate: 45
                    }}
                }},
                yAxis: {{
                    type: 'value',
                    axisLine: {{ lineStyle: {{ color: '#00d4ff' }} }},
                    axisLabel: {{ color: '#fff' }},
                    splitLine: {{ lineStyle: {{ color: 'rgba(0, 212, 255, 0.1)' }} }}
                }},
                series: [{{
                    type: 'bar',
                    data: highRiskRegions.map(item => ({{
                        value: item.value,
                        itemStyle: {{
                            color: item.risk === '高' ? '#ff6b6b' : '#ffd93d'
                        }}
                    }})),
                    animationDelay: function (idx) {{
                        return idx * 100;
                    }}
                }}],
                animationEasing: 'elasticOut'
            }};
            chart.setOption(option);
        }}

        // 5. 增长率变化趋势图
        function initGrowthChart() {{
            const chart = echarts.init(document.getElementById('growthChart'));
            const option = {{
                backgroundColor: 'transparent',
                tooltip: {{
                    trigger: 'axis',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    textStyle: {{ color: '#fff' }}
                }},
                grid: {{
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                }},
                xAxis: {{
                    type: 'category',
                    data: chartData.dates,
                    axisLine: {{ lineStyle: {{ color: '#00d4ff' }} }},
                    axisLabel: {{ 
                        color: '#fff',
                        rotate: 45,
                        interval: Math.floor(chartData.dates.length / 10)
                    }}
                }},
                yAxis: {{
                    type: 'value',
                    axisLine: {{ lineStyle: {{ color: '#00d4ff' }} }},
                    axisLabel: {{ 
                        color: '#fff',
                        formatter: '{{value}}%'
                    }},
                    splitLine: {{ 
                        lineStyle: {{ color: 'rgba(0, 212, 255, 0.1)' }}
                    }}
                }},
                series: [
                    {{
                        name: '增长率',
                        type: 'line',
                        data: growthRates,
                        smooth: true,
                        lineStyle: {{
                            color: '#00d4ff',
                            width: 3
                        }},
                        areaStyle: {{
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {{ offset: 0, color: 'rgba(0, 212, 255, 0.3)' }},
                                {{ offset: 1, color: 'rgba(0, 212, 255, 0.1)' }}
                            ])
                        }},
                        markLine: {{
                            data: [{{ yAxis: 0, name: '0线' }}],
                            lineStyle: {{ color: '#ff6b6b', type: 'dashed' }}
                        }},
                        animationDelay: function (idx) {{
                            return idx * 10;
                        }}
                    }}
                ],
                animationEasing: 'elasticOut'
            }};
            chart.setOption(option);
        }}

        // 6. 活跃病例趋势图
        function initActiveTrendChart() {{
            const chart = echarts.init(document.getElementById('activeTrendChart'));
            const option = {{
                backgroundColor: 'transparent',
                tooltip: {{
                    trigger: 'axis',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    textStyle: {{ color: '#fff' }}
                }},
                grid: {{
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                }},
                xAxis: {{
                    type: 'category',
                    data: chartData.dates,
                    axisLine: {{ lineStyle: {{ color: '#00d4ff' }} }},
                    axisLabel: {{ 
                        color: '#fff',
                        rotate: 45,
                        interval: Math.floor(chartData.dates.length / 10)
                    }}
                }},
                yAxis: {{
                    type: 'value',
                    axisLine: {{ lineStyle: {{ color: '#00d4ff' }} }},
                    axisLabel: {{ color: '#fff' }},
                    splitLine: {{ lineStyle: {{ color: 'rgba(0, 212, 255, 0.1)' }} }}
                }},
                series: [
                    {{
                        name: '活跃病例',
                        type: 'line',
                        data: chartData.activeCases,
                        smooth: true,
                        lineStyle: {{
                            color: '#ffd93d',
                            width: 3
                        }},
                        areaStyle: {{
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {{ offset: 0, color: 'rgba(255, 217, 61, 0.3)' }},
                                {{ offset: 1, color: 'rgba(255, 217, 61, 0.1)' }}
                            ])
                        }},
                        animationDelay: function (idx) {{
                            return idx * 10;
                        }}
                    }}
                ],
                animationEasing: 'elasticOut'
            }};
            chart.setOption(option);
        }}

        // 7. 地图热力图（简化版，使用散点图模拟）
        function initMapChart() {{
            const chart = echarts.init(document.getElementById('mapChart'));

            // 模拟香港各区的坐标数据
            const mapData = chartData.regions.map((region, index) => ({{
                name: region,
                value: [
                    114.1 + Math.random() * 0.3, // 经度
                    22.2 + Math.random() * 0.3,   // 纬度
                    chartData.regionConfirmed[index]
                ]
            }}));

            const option = {{
                backgroundColor: 'transparent',
                tooltip: {{
                    trigger: 'item',
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    textStyle: {{ color: '#fff' }},
                    formatter: function(params) {{
                        return `${{params.name}}<br/>累计确诊: ${{params.value[2].toLocaleString()}}`;
                    }}
                }},
                xAxis: {{
                    type: 'value',
                    show: false,
                    min: 113.8,
                    max: 114.5
                }},
                yAxis: {{
                    type: 'value',
                    show: false,
                    min: 22.1,
                    max: 22.6
                }},
                series: [{{
                    type: 'scatter',
                    data: mapData,
                    symbolSize: function(data) {{
                        return Math.sqrt(data[2]) * 2;
                    }},
                    itemStyle: {{
                        color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
                            {{ offset: 0, color: 'rgba(255, 107, 107, 0.8)' }},
                            {{ offset: 1, color: 'rgba(255, 107, 107, 0.1)' }}
                        ]),
                        borderColor: '#ff6b6b',
                        borderWidth: 2
                    }},
                    label: {{
                        show: true,
                        formatter: '{{b}}',
                        position: 'top',
                        color: '#fff',
                        fontSize: 10
                    }},
                    animationDelay: function (idx) {{
                        return idx * 100;
                    }}
                }}],
                animationEasing: 'elasticOut'
            }};
            chart.setOption(option);
        }}

        // 响应式调整
        window.addEventListener('resize', function() {{
            const charts = [
                'trendChart', 'regionChart', 'riskChart', 
                'warningChart', 'growthChart', 'activeTrendChart', 'mapChart'
            ];
            charts.forEach(chartId => {{
                const chart = echarts.getInstanceByDom(document.getElementById(chartId));
                if (chart) {{
                    chart.resize();
                }}
            }});
        }});

        // 控制功能
        function changeTimeRange(range) {{
            console.log('切换时间范围:', range);
            // 这里可以根据时间范围重新加载数据
        }}

        function exportData() {{
            console.log('导出数据');
            // 这里可以实现数据导出功能
        }}

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {{
            setTimeout(initAllCharts, 500);
        }});
    </script>
</body>
</html>"""

    return html_template


def main():
    print("=" * 80)
    print("创建香港疫情数据可视化大屏")
    print("=" * 80)

    # 处理数据
    chart_data = process_data_for_dashboard()

    # 创建HTML文件
    html_content = create_dashboard_html(chart_data)

    # 保存文件
    output_file = r"e:\Projects\program-py\LEARN-数据分析\CASE-dashboard_epidemic\epidemic_dashboard_advanced.html"
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_content)

    print(f"可视化大屏已创建: {output_file}")
    print(f"数据时间范围: {chart_data['dates'][0]} 到 {chart_data['dates'][-1]}")
    print(f"涵盖地区数: {len(chart_data['regions'])}")
    print(f"累计确诊: {chart_data['stats']['totalConfirmed']:,}")
    print(f"今日新增: {chart_data['stats']['newConfirmed']:,}")

    # 在浏览器中打开
    import webbrowser
    webbrowser.open(f'file://{output_file}')

    print("\n" + "=" * 80)
    print("大屏已在浏览器中打开!")
    print("=" * 80)


if __name__ == "__main__":
    main()